package com.example.service.impl;

import com.example.entity.User;
import com.example.entity.example.UserExample;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Override
    public User getUserByUsername(String username) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        return (users == null || users.isEmpty()) ? null : users.get(0);
    }

    @Override
    public List<User> getByExampleWithLimit(UserExample example, Integer curPage, Integer pageSize) {
        int begin = (curPage - 1) * pageSize;
        return userMapper.selectByExampleWithLimit(example, begin, pageSize);
    }

    @Override
    public long getCountByExample(UserExample example) {
        return userMapper.countByExample(example);
    }

    @Override
    public User getUserByIdOrPhone(String idOrPhone) {
        UserExample example = new UserExample();
        if (idOrPhone.length() == 11) {
            example.or().andPhoneEqualTo(idOrPhone);
        } else {
            int id = 0;
            try {
                id = Integer.parseInt(idOrPhone);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            example.or().andIdEqualTo(id);
        }
        List<User> userList = userMapper.selectByExample(example);
        return userList == null || userList.isEmpty() ? null : userList.get(0);
    }

    @Override
    public void addUser(User user) {
        userMapper.insert(user);
    }

    @Override
    public void removeById(Integer id) {
        userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void updateById(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }
}
